/**
 * CSVParser.java
 * 
 * @authors: Connor Gordon, Difan Zhao, Kathleen Lan, Patrick Royal
 */

package io;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import model.Element;
import model.StockElement;


/**
 * 
 * @author Group 8
 * 
 */
public class CSVParser extends DataParser {

    private static final String OUR_EXT = ".csv";

    /**
     * Constructor for CSVParser from url.
     * 
     * @param name name of file
     * @param id unique id for the parser
     * @param url location of file
     */
    public CSVParser (String name, String id, String url) {
        super(name, id, url, OUR_EXT);
    }

    /**
     * Constructor for CSVParser from file.
     * 
     * @param name name of file
     * @param id unique id for the parser
     * @param f file itself
     */
    public CSVParser (String name, String id, File f) {
        super(name, id, f);
    }

    @Override
    public Element parseData () {
        Map<String, List<Double>> data = new HashMap<String, List<Double>>();
        try {
            BufferedReader br = new BufferedReader(new FileReader(getFile()));
            StringTokenizer st = null;
            String dataLine = br.readLine();
            int row = 0;
            Map<Integer, String> posToLabel = new HashMap<Integer, String>();
            while (dataLine != null) {
                st = new StringTokenizer(dataLine, ",");
                int col = 0;
                while (st.hasMoreTokens()) {
                    String key = st.nextToken();
                    if (col != 0) {
                        if (row == 0) {
                            data.put(key.toLowerCase(), new LinkedList<Double>());
                            posToLabel.put(col, key.toLowerCase());
                        }
                        else {
                            data.get(posToLabel.get(col)).add(Double.parseDouble(key));
                        }
                    }
                    col++;
                }
                dataLine = br.readLine();
                row++;
            }
            br.close();
            if (getFile().getName().contains("loadin")) {
                getFile().delete();
            }
        }
        catch (IOException e) {
            System.out.println("Difficulty converting .csv file to Element");
        }

        return new StockElement(getName(), getId(), Collections.unmodifiableMap(data));
    }

}
